import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Table, Popover, Popconfirm, Dropdown, notification } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import type { QueryBigClientListParams, BigClient } from './services';
import { BigClientOrgType, BigClientStatus, queryChargeList, updateStatus, resetPsw } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';
import Ellipsis from '@/components/Ellipsis';
import { history } from '@umijs/max'
import ChargeModal, { ChargeModalProps } from './components/ChargeModal'
import { jump2target } from '@/utils/common';

const BigClientPage: React.FC = () => {
  const [searchForm] = Form.useForm<QueryBigClientListParams>()
  const [searchParams, setSearchParams] = useState<QueryBigClientListParams>({
    pageNum: 1, pageSize: 10,
  })
  const list = useRequest(() => queryChargeList(searchParams), {
    refreshDeps: [searchParams],
  })
  const { runAsync: resetPswAsync } = useRequest(resetPsw, {manual: true, onSuccess: () => {
    notification.success({
      message: '密码重置成功'
    })
  }})
  const { runAsync: updateStatusAsync } = useRequest(updateStatus, {manual: true})
  const [chargeModalProps, setChargeModalProps] = useState<ChargeModalProps>()

  const openEditPage = (title: string, type: string, id?: string) => {
    jump2target(`/bigC/bigCList/edit?type=${type}&id=${id || ''}`, {needRefresh: true})
    sessionStorage.setItem('__/bigC/bigCList/edit_title', title)
  }

  const openChargeModal = (record: BigClient) => {
    setChargeModalProps({id: record.id, balance: record.amount})
  }

  const openChargeList = (record: BigClient) => {
    jump2target(`/bigC/bigCCharge?companyName=${record.companyName}`, {needRefresh: true})
  }

  const onChargeModalCancel = (refresh: boolean) => {
    if (refresh) list.refresh()
    setChargeModalProps(undefined)
  }

  const onFinish = (formValues: any) => {
    setSearchParams({
      ...searchParams,
      companyName: formValues.companyName,
      loginPhone: formValues.loginPhone,
      orgCode: formValues.orgCode,
      pageNum: 1,
    })
  }

  const columns: ColumnsType<BigClient> = [
    {
      title: '名称',
      dataIndex: 'companyName',
      width: 160,
    },
    {
      title: '余额(元)',
      dataIndex: 'amount',
      width: 100,
    },
    {
      title: '证件类型',
      dataIndex: 'orgType',
      width: 100,
      render: val => BigClientOrgType[val],
    },
    {
      title: '证件号码',
      dataIndex: 'orgCode',
      width: 160,
    },
    {
      title: '登录账号',
      dataIndex: 'loginPhone',
      width: 120,
    },
    {
      title: '地址',
      dataIndex: 'cityName',
      width: 160,
      render: (val, record) => {
        return <Popover content={`${val}-${record.companyAddress}`}>
          <Ellipsis>{`${val}-${record.companyAddress}`}</Ellipsis>
        </Popover>
      },
    },
    {
      title: '电话',
      dataIndex: 'companyPhone',
      width: 120,
    },
    {
      title: '负责人',
      dataIndex: 'chiefName',
      width: 100,
    },
    {
      title: '负责人电话',
      dataIndex: 'chiefPhone',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 120,
      render: val => val && dayjs(val).format('YYYY-MM-DD'),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: val => BigClientStatus[val],
    },
    {
      title: '操作',
      key: 'operations',
      width: 220,
      fixed: 'right',
      render: (_, record) => {
        const items = [
          {key: 'edit', label: <a onClick={() => openEditPage('编辑企业', 'edit', record.id)}>编辑</a>},
        ]
        if (record.status === BigClientStatus.启用) {
          items.push({key: 'disabled', label: <Popconfirm
            title={`确定禁用企业: ${record.companyName} 吗？`}
            onConfirm={() => updateStatusAsync({id: record.id, status: BigClientStatus.禁用}).then(list.refresh)}
            okText="禁用"
            cancelText="取消"
          >
            <a>禁用</a>
          </Popconfirm>})
        } else {
          items.push({key: 'enable', label: <Popconfirm
            title={`确定启用企业: ${record.companyName} 吗？`}
            onConfirm={() => updateStatusAsync({id: record.id, status: BigClientStatus.启用}).then(list.refresh)}
            okText="启用"
            cancelText="取消"
          >
            <a>启用</a>
          </Popconfirm>})
        }
        return <Space>
          <a onClick={() => openChargeModal(record)}>充值</a>
          <a onClick={() => openChargeList(record)}>变动记录</a>
          <Popconfirm
            title={`确定重置企业: ${record.companyName} 的密码吗？重置后密码为“123456”`}
            onConfirm={() => resetPswAsync({id: record.id})}
            okText="重置"
            cancelText="取消"
          >
            <a>重置密码</a>
          </Popconfirm>
          <Dropdown menu={{items}}>
            <a>...</a>
          </Dropdown>
        </Space>
      }
    },
  ]

  useEffect(() => {
    const refresh = () => {
      list.refresh()
    }
    window.addEventListener('refreshBigClientList', refresh)
    return () => {
      window.removeEventListener('refreshBigClientList', refresh)
    }
  }, []);
  
  return (
    <div className='container'>
      <div className="card search-card">
        <div className="toolbar">
          <Space>
            <Button type='primary' onClick={() => openEditPage('新建企业', 'add')}>新建企业</Button>
          </Space>
        </div>
        <div className="form-area">
          <Form name='searchBigClientForm' form={searchForm} onFinish={onFinish}>
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='名称' name='companyName'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='登录账号' name='loginPhone'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='身份证/组织机构代码' name='orgCode'>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<BigClient>
          rowKey='id'
          loading={list.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
      <ChargeModal
        {...chargeModalProps}
        onCancel={onChargeModalCancel}
      />
    </div>
  );
};

export default BigClientPage;
